﻿using Aspose.Cells;
using Aspose.Cells.Drawing;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Tecarrier.Tools
{
    public partial class frmPdfTools : Form
    {
        public frmPdfTools()
        {
            AutoScaleMode = AutoScaleMode.Dpi;
            InitializeComponent();
        }

        #region Photo => PDF

        private void btnSourceFolder_Click(object sender, EventArgs e)
        {
            // 创建一个FolderBrowserDialog对象
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 设置FolderBrowserDialog的属性
            folderBrowserDialog.Description = "选择文件夹";
            folderBrowserDialog.ShowNewFolderButton = false;
            folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            // 打开文件夹选择对话框
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                // 获取选中的文件夹路径数组
                string selectedFolder = folderBrowserDialog.SelectedPath;

                // 清空ListView中的项
                this.txtPhotoFolders.Clear();

                var folders = new DirectoryInfo(selectedFolder).GetDirectories();

                // 将选中的文件夹路径添加到ListView中
                StringBuilder sb = new StringBuilder();
                foreach (var folder in folders)
                {
                    sb.AppendLine(folder.FullName);
                }
                txtPhotoFolders.Text = sb.ToString();
            }
        }

        private void btnTargetFolder_Click(object sender, EventArgs e)
        {
            // 创建一个FolderBrowserDialog对象
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 设置FolderBrowserDialog的属性
            folderBrowserDialog.Description = "选择文件夹";
            folderBrowserDialog.ShowNewFolderButton = false;
            folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            // 打开文件夹选择对话框
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                // 获取选中的文件夹路径数组
                string selectedFolder = folderBrowserDialog.SelectedPath;

                this.txtPdfFolder.Text = selectedFolder;
            }
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            btnConvert.Enabled = false;

            if (string.IsNullOrEmpty(txtPhotoFolders.Text?.Trim()))
            {
                MessageBox.Show("The source folder is invalid.");
                btnConvert.Enabled = true;
                return;
            }
            if (!Directory.Exists(txtPdfFolder.Text))
            {
                MessageBox.Show("The target folder is invalid.");
            }
            else
            {
                var lines = txtPhotoFolders.Lines;

                //设置进度条基础属性
                this.spbProcess.Value = 0;
                this.spbProcess.Style = ProgressBarStyle.Blocks;
                this.spbProcess.Maximum = lines.Length;
                this.spbProcess.Minimum = 0;
                this.spbProcess.MarqueeAnimationSpeed = 100;
                this.spbProcess.Step = 1;
                this.sslProcess.Text = "0%";
                this.spbProcess.Visible = true;
                this.sslProcess.Visible = true;
                foreach (var line in lines)
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        var imgFolderName = new DirectoryInfo(line).Name;
                        var pdfName = imgFolderName + "_PHT.pdf";
                        var pdfPath = System.IO.Path.Combine(txtPdfFolder.Text, pdfName);
                        StringBuilder sb = new StringBuilder(this.txtConvertResult.Text);

                        if (ckbOverwrite.Checked == false && File.Exists(pdfPath))
                        {
                            this.txtConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {pdfName} -- Skip").ToString();
                        }
                        else
                        {
                            var compressionRatio = Convert.ToDouble(nudCompressionRatio.Value / 100);
                            var result = PhotoToPDFHelper.GeneratePdfFile(line, pdfPath, compressionRatio);

                            switch (result)
                            {
                                case ConvertResult.Success:
                                    this.txtConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {pdfName} -- Success").ToString();
                                    break;
                                case ConvertResult.Failed:
                                    this.txtConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {pdfName} -- Failed").ToString();
                                    break;
                                case ConvertResult.NoPhotoes:
                                    this.txtConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {imgFolderName} -- No Photoes").ToString();
                                    break;
                            }
                        }

                        this.txtConvertResult.Text = sb.AppendLine($"-------------------------------------------------------").ToString();
                        this.txtConvertResult.SelectionStart = this.txtConvertResult.Text.Length;
                        this.txtConvertResult.ScrollToCaret();
                        Application.DoEvents();
                    }

                    //更新进度条进度状态,当进度条为跑马灯模式时（ProgressBarStyle.Marquee）不可能调用该方法
                    this.spbProcess.PerformStep();

                    //设置进度百分比
                    double dCount = lines.Length, dProg = this.spbProcess.Value;
                    this.sslProcess.Text = ((dProg / dCount) * 100).ToString("N0") + "%";
                }

                MessageBox.Show("All directories have been converted.");

                if (ckbOpenTarget.Checked)
                {
                    System.Diagnostics.Process.Start(txtPdfFolder.Text);
                }
            }

            btnConvert.Enabled = true;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.btnReset.Enabled = false;
            this.txtPhotoFolders.Clear();
            this.txtPdfFolder.Clear();
            this.txtConvertResult.Clear();
            this.spbProcess.Visible = false;
            this.sslProcess.Visible = false;
            this.btnReset.Enabled = true;
        }

        #endregion

        #region Execl => PDF

        private void btnExcelToPdf_Click(object sender, EventArgs e)
        {
            btnExcelToPdf.Enabled = false;
            spbProcess.Value = 0;
            spbProcess.Style = ProgressBarStyle.Blocks;
            spbProcess.Minimum = 0;
            spbProcess.MarqueeAnimationSpeed = 100;
            spbProcess.Step = 1;
            sslProcess.Text = "0%";
            spbProcess.Visible = true;
            sslProcess.Visible = true;
            txtExcelConvertResult.Clear();
            if (string.IsNullOrEmpty(txtSourceExcel.Text?.Trim()))
            {
                MessageBox.Show("Please select an excel source file.");
                txtSourceExcel.Focus();
                btnExcelToPdf.Enabled = true;
                return;
            }
            else
            {
                if (!File.Exists(txtSourceExcel.Text?.Trim()))
                {
                    MessageBox.Show("The Excel file does not exist, please select it again.");
                    txtSourceExcel.Focus();
                    btnExcelToPdf.Enabled = true;
                    return;
                }
            }

            if (string.IsNullOrEmpty(txtReportFolder.Text?.Trim()))
            {
                MessageBox.Show("Please select a folder where you want to save the pdf.");
                txtReportFolder.Focus();
                btnExcelToPdf.Enabled = true;
                return;
            }
            else
            {
                if (!Directory.Exists(txtReportFolder.Text?.Trim()))
                {
                    try
                    {
                        Directory.CreateDirectory(txtReportFolder.Text.Trim());
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("The PDF output folder path is invalid, please select it again.");
                        txtReportFolder.Focus();
                        btnExcelToPdf.Enabled = true;
                        return;
                    }
                }
            }

            new Aspose.Cells.License().SetLicense(new MemoryStream(Convert.FromBase64String("PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZWxvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4yMDA2MDIwMTI2MzM8L09yZGVySUQ+CiAgICA8VXNlcklEPjEzNDk3NjAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+OTM2ZTVmZDEtODY2Mi00YWJmLTk1YmQtYzhkYzBmNTNhZmE2PC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0aW9uRXhwaXJ5PjIwMjEwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvbj4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+CiAgPFNpZ25hdHVyZT5wSkpjQndRdnYxV1NxZ1kyOHFJYUFKSysvTFFVWWRrQ2x5THE2RUNLU0xDQ3dMNkEwMkJFTnh5L3JzQ1V3UExXbjV2bTl0TDRQRXE1aFAzY2s0WnhEejFiK1JIWTBuQkh1SEhBY01TL1BSeEJES0NGbWg1QVFZRTlrT0FxSzM5NVBSWmJRSGowOUNGTElVUzBMdnRmVkp5cUhjblJvU3dPQnVqT1oyeDc4WFE9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4=")));

            Workbook workbook = new Workbook(txtSourceExcel.Text);
            Worksheet worksheet = workbook.Worksheets[0];
            var worksheets = workbook.Worksheets;
            var cells = worksheet.Cells;

            spbProcess.Maximum = cells.MaxDataRow - 11;

            var customerName = worksheets.Names["CUSTOMER"].GetRange().Value;
            var lessorName = worksheets.Names["LESSOR"].GetRange().Value;
            var releaseReference = worksheets.Names["RELEASE_REFERENCE"].GetRange().Value;
            var containerModel = worksheets.Names["RELEASE_REFERENCE"].GetRange().Value;
            var orderQuantity = worksheets.Names["ORDER_QTY"].GetRange().Value;
            var depotName = worksheets.Names["DEPOT"].GetRange().Value;
            var depotAddress = worksheets.Names["DEPOT_ADDRESS"].GetRange().Value;
            var inspectionCriteria = worksheets.Names["INSPECTION_CRITERIA"].GetRange().Value;

            for (int row = 12; row <= cells.MaxDataRow + 1; row++)
            {
                StringBuilder sb = new StringBuilder(txtExcelConvertResult.Text);
                try
                {
                    var unitNumber = cells["B" + row].Value;
                    var inspectionDate = cells["C" + row].Value;
                    var equipSubType = cells["D" + row].Value;
                    var mgw = cells["E" + row].Value;
                    var tare = cells["F" + row].Value;
                    var manufactureDate = cells["G" + row].Value;
                    var csdData = cells["H" + row].Value;
                    var exteriorColor = cells["J" + row].Value;
                    var generalComments = cells["L" + row].Value;
                    var inspectorName = cells["M" + row].Value;
                    var manufacturer = cells["N" + row].Value;

                    // 从嵌入资源中获取Excel文件流
                    Assembly assembly = Assembly.GetExecutingAssembly();
                    Stream excelStream = assembly.GetManifestResourceStream("Tecarrier.Tools.REPORT.xlsx");
                    Workbook targetWorkbook = new Workbook(excelStream);
                    Worksheet targetWorksheet = targetWorkbook.Worksheets[0];
                    var targetCells = targetWorksheet.Cells;

                    targetCells["K4"].PutValue(customerName);

                    targetCells["A7"].PutValue(unitNumber);
                    targetCells["G7"].PutValue(lessorName);
                    targetCells["M7"].PutValue(releaseReference);
                    targetCells["S7"].PutValue(inspectionDate);
                    targetCells["Y7"].PutValue(exteriorColor);

                    targetCells["A10"].PutValue(containerModel);
                    targetCells["G10"].PutValue(manufacturer);
                    targetCells["M10"].PutValue(manufactureDate);
                    targetCells["S10"].PutValue(depotName);
                    targetCells["Y10"].PutValue(depotAddress);

                    targetCells["A13"].PutValue(equipSubType);
                    targetCells["G13"].PutValue(tare);
                    targetCells["M13"].PutValue(mgw);
                    targetCells["S13"].PutValue(csdData);

                    targetCells["A17"].PutValue(generalComments);

                    targetCells["K46"].PutValue(inspectionCriteria);

                    targetCells["E48"].PutValue(inspectorName);

                    var pdfName = $"{unitNumber}_RPT.pdf";
                    var pdfPath = txtReportFolder.Text?.Trim() + "\\" + pdfName;

                    if (File.Exists(pdfPath))
                    {
                        if (ckbOverwrite_ExcelConvert.Checked)
                        {
                            targetWorkbook.Save(pdfPath, SaveFormat.Pdf);
                        }
                    }
                    else
                    {
                        targetWorkbook.Save(pdfPath, SaveFormat.Pdf);
                    }

                    if (ckbOverwrite_ExcelConvert.Checked == false && File.Exists(pdfPath))
                    {
                        txtExcelConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {pdfName} -- Skip").ToString();
                    }
                    else
                    {
                        targetWorkbook.Save(pdfPath, SaveFormat.Pdf);
                        txtExcelConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {pdfName} -- Success").ToString();
                    }
                }
                catch (Exception)
                {
                    txtExcelConvertResult.Text = sb.AppendLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: Row {row} conversion failed").ToString();
                }

                txtExcelConvertResult.Text = sb.AppendLine($"-------------------------------------------------------").ToString();
                txtExcelConvertResult.SelectionStart = txtExcelConvertResult.Text.Length;
                txtExcelConvertResult.ScrollToCaret();
                Application.DoEvents();

                //更新进度条进度状态,当进度条为跑马灯模式时（ProgressBarStyle.Marquee）不可能调用该方法
                spbProcess.PerformStep();

                //设置进度百分比
                double dCount = cells.MaxDataRow - 11, dProg = spbProcess.Value;
                sslProcess.Text = ((dProg / dCount) * 100).ToString("N0") + "%";
            }

            MessageBox.Show("All records have been converted.");

            if (ckbOpenFolder_ExcelConvert.Checked)
            {
                System.Diagnostics.Process.Start(txtReportFolder.Text?.Trim());
            }

            btnExcelToPdf.Enabled = true;
        }

        private void btnSourceExcel_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel Files|*.xlsx;*.xls";
            openFileDialog.Title = "Select an Excel File";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string selectedFilePath = openFileDialog.FileName;
                // 在这里可以对所选的Excel文件进行处理
                // 例如，可以将其读取到DataTable或直接操作Excel数据
                txtSourceExcel.Text = selectedFilePath;
            }
        }

        private void btnReportFolder_Click(object sender, EventArgs e)
        {
            // 创建一个FolderBrowserDialog对象
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 设置FolderBrowserDialog的属性
            folderBrowserDialog.Description = "选择文件夹";
            folderBrowserDialog.ShowNewFolderButton = false;
            folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            // 打开文件夹选择对话框
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                // 获取选中的文件夹路径数组
                string selectedFolder = folderBrowserDialog.SelectedPath;

                this.txtReportFolder.Text = selectedFolder;
            }
        }

        private void btnReset_ExcelTool_Click(object sender, EventArgs e)
        {
            this.btnReset_ExcelTool.Enabled = false;
            this.txtSourceExcel.Clear();
            this.txtReportFolder.Clear();
            this.txtExcelConvertResult.Clear();
            this.spbProcess.Visible = false;
            this.sslProcess.Visible = false;
            this.btnReset_ExcelTool.Enabled = true;
        }

        #endregion


    }

}
